import 'dart:async';

import 'package:flutter_demo/core/common/event/http_error_event.dart';
import 'package:flutter_demo/core/common/event/index.dart';
import 'package:flutter_demo/core/common/net/code.dart';
import 'package:flutter_demo/core/service/auth_service.dart';
import 'package:get/get.dart';

class EventService extends GetxService {
  late StreamSubscription stream;
  @override
  void onInit() {
    //处理异常提示
    stream = eventBus.on<HttpErrorEvent>().listen((event) {
      errorHandleFunction(event.code, event.message);
    });
    super.onInit();
  }

  @override
  void onClose() {
    stream.cancel();
    super.onClose();
  }

  ///网络错误提醒
  void errorHandleFunction(int code, String message) {
    switch (code) {
      case Code.NETWORK_ERROR:
        showToast('网络错误', message);
        break;
      case 301:
        showToast('需要登录', message);
        AuthService.to.logout();
        //Get.toNamed(Routes.LOGIN);
        break;
      case 403:
        showToast('权限错误', message);
        break;
      case 404:
        showToast('404错误', message);
        break;
      case Code.SYS_ERRO:
        showToast('系统错误', message);
        break;
      case Code.NETWORK_TIMEOUT:
        //超时
        showToast('请求超时', message);
        break;
      default:
        showToast("异常", message);
        break;
    }
  }

  void showToast(String tiltle, String message) {
    Get.log(message, isError: true);
    Get.snackbar(
      tiltle,
      message,
    );
  }
}
